package com.example.mysaat.handle_utils;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.WindowManager;

import com.example.mysaat.service_menu_manual_test.allActivities.Camera_MainActivity;

import java.util.ArrayList;
import java.util.List;

public class SquareCameraFrontPreview extends SurfaceView {

    private static final String TAG = SquareCameraPreview.class.getSimpleName();
    private static final int INVALID_POINTER_ID = -1;

    private static final int FOCUS_SQR_SIZE = 100;
    private static final int FOCUS_MAX_BOUND =1000;
    private static final int FOCUS_MIN_BOUND = -FOCUS_MAX_BOUND;

    private static final double ASPECT_RADIO = 3.0/4.0;
    private Camera myCamera;

    private float mLastTouchX;
    private float mLastTouchY;

    //for focus
    public boolean mIsFocus;
    private Camera.Area  mFocusArea;
    private ArrayList<Camera.Area> mFocusAreas;                 //一系类的聚焦区域
    private Camera.AutoFocusCallback autoFocusCallback;         //自动对焦回调
    public boolean isPreviewing = false;                      //是预览？
    private Context mContext;
    private Camera_MainActivity cameraActivity;


    public void setAutoFocusCallBack(Camera.AutoFocusCallback autoFocusCallBack){
        this.autoFocusCallback = autoFocusCallBack;
    }

    public void setCamera(Camera camera){
        myCamera = camera;
        Log.i(TAG,"Camera is set by machine  75 行");
    }
    public SquareCameraFrontPreview(Context context) {
        super(context);
        init(context);
    }

    public SquareCameraFrontPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SquareCameraFrontPreview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context){
        this.mContext = context;
        mFocusArea = new Camera.Area(new Rect(),1000);
        mFocusAreas = new ArrayList<Camera.Area>();
        mFocusAreas.add(mFocusArea);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width  = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width,height);
    }

    //
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        final int  action = event.getAction();
        switch (action & MotionEvent.ACTION_MASK){
            case MotionEvent.ACTION_DOWN: {
                mIsFocus = true;
                mLastTouchX = event.getX();
                mLastTouchY = event.getY();
                break;
            }
            case MotionEvent.ACTION_UP:{
                Point point = new Point((int)event.getX(),(int)event.getY());
                if(mIsFocus){
                    if(myCamera!=null){
                        //handle focus
//                        handleFocus(myCamera.getParameters(),point);
                    }
                }
                break;
            }
            case MotionEvent.ACTION_POINTER_DOWN:{
                if(myCamera !=null && this.getVisibility() == VISIBLE &&isPreviewing){
                    myCamera.cancelAutoFocus();
                }
                mIsFocus = false;
                break;
            }
            case MotionEvent.ACTION_CANCEL:{
                break;
            }
        }
        return true;
    }

    /*private void handleFocus(Camera.Parameters params,Point point){
        float x = mLastTouchX;
        float Y = mLastTouchX;

        Camera.Parameters parameters =  myCamera.getParameters();
        if(parameters.getMaxNumFocusAreas()<0){
            myCamera.autoFocus(autoFocusCallback);
            return;
        }
        myCamera.cancelAutoFocus();
        List<Camera.Area> areas = new ArrayList<Camera.Area>();
        List<Camera.Area> areaMetrix = new ArrayList<Camera.Area>();
        Camera.Size previewSize = parameters.getPreviewSize();
        //在点击的地方进行聚焦
        Rect focusRect = calculateTapArea(point.x,point.y,1.0f,previewSize);
        Rect metrixRect = calculateTapArea(point.x,point.y,1.5f,previewSize);

        areas.add(new Camera.Area(focusRect,1000));
        areaMetrix.add(new Camera.Area(metrixRect,1000));
        parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
        parameters.setMeteringAreas(areaMetrix);
//        parameters.setFocusAreas(areas);

            Log.i(TAG,"the machine start to auto focus");
            myCamera.setParameters(parameters);
            myCamera.autoFocus(autoFocusCallback);

    }
*/

    private Rect calculateTapArea(float x,float y,float coefficient,Camera.Size previewSize){
        Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int screenHeight = display.getHeight();
        int screenWidht = display.getWidth();
        float focusSize = 200;
        int areaSize = Float.valueOf(focusSize*coefficient).intValue();
        int centerY = 0;
        int centerX = 0;
        centerY = (int)(y/ screenHeight*2000-1000);
        centerX = (int)(x/ screenWidht*2000-1000);
        // clamp means fixed somethings
        int left = clamp(centerX - areaSize/2,FOCUS_MIN_BOUND,FOCUS_MAX_BOUND);
        int top = clamp(centerY-areaSize/2,FOCUS_MIN_BOUND,FOCUS_MAX_BOUND);
        RectF rectF = new RectF(left,top,left+areaSize,top+areaSize);
        return new Rect(Math.round(rectF.left),Math.round(top),Math.round(rectF.right),Math.round(rectF.bottom));
    }

    public static int clamp(int x,int min,int max){
        if(x>max){
            return max;
        }

        if(x<min){
            return min;
        }
        return x;
    }
}
